import cv2
import numpy as np
img = cv2.imread('output.png')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

#contours部分
_, binary2 = cv2.threshold(gray, 225, 255, cv2.THRESH_BINARY)
#去噪
kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (5, 5))
binary2 = cv2.morphologyEx(binary2, cv2.MORPH_OPEN, kernel)
#找最外层轮廓
contours, hierarchy = cv2.findContours(
    binary2,
    cv2.RETR_EXTERNAL,
    cv2.CHAIN_APPROX_SIMPLE)

#不使用拟合直接调亮度值的框选
green_out = img.copy()
for cnt in contours:
    area = cv2.contourArea(cnt)
    if area < 500:    # 去小噪声
        continue
    cv2.drawContours(green_out, [cnt], -1, (0, 255, 0), 2)

    cv2.imshow('p2_green', green_out)
    cv2.imwrite('p2_green.png', green_out)


#rectangle部分,做出拟合
red_result = img.copy()
for contour in contours:
    area = cv2.contourArea(contour)
    if area < 500:
        continue
    x,y,w,h = cv2.boundingRect(contour)
    cv2.rectangle(red_result, (x, y), (x + w, y + h), (0, 0, 255), 2)
    # approx部分
    #epsilon = 0.03 * cv2.arcLength(contour, True)
    #approx = cv2.approxPolyDP(contour, epsilon, True)
    #cv2.polylines(result, [approx], True, (0, 0, 255), 1)
    cv2.imshow('contours', red_result)
    cv2.imwrite('contours.png', red_result)


cv2.waitKey(0)
cv2.destroyAllWindows()